<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="测站编码" prop="stCd">
        <el-input
          v-model="queryParams.stCd"
          placeholder="请输入测站编码"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="测站名称" prop="stName">
        <el-input
          v-model="queryParams.stName"
          placeholder="请输入测站名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="测站分类" prop="stClassification">
        <el-select v-model="queryParams.stClassification" placeholder="测站分类" clearable size="small" :style="{width: '100%'}">
          <el-option v-for="dict in dict.type.st_classification"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="测站类型" prop="stType">
        <el-select v-model="queryParams.stType" placeholder="测站类型" clearable size="small" :style="{width: '100%'}">
          <el-option v-for="dict in dict.type.st_type"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleInitCache"
          v-hasPermi="['system:role:export']"
        >刷新缓存
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="false"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getPage"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="page" @selection-change="handleSelectionChange">
      <el-table-column type="selection" fixed width="55" align="center"/>
      <el-table-column label="测站编码" fixed prop="stCd" width="150"/>
      <el-table-column label="测站名称" fixed prop="stName" :show-overflow-tooltip="true" width="240"/>
      <el-table-column label="测站分类" fixed prop="stClassificationCn"  width="150"/>
      <el-table-column label="测站类型" fixed prop="stTypeCn" :show-overflow-tooltip="true" width="150"/>
      <el-table-column label="上报频率（分钟/条）" fixed prop="submitFrequency" width="180"/>
      <el-table-column label="行业类别" prop="industryTypeCn" :show-overflow-tooltip="true" width="150"/>
      <el-table-column label="建设单位" :show-overflow-tooltip="true" prop="constructionUnit" width="200"/>
      <el-table-column label="管理单位" :show-overflow-tooltip="true" prop="managementUnit" width="200"/>
      <el-table-column label="运维单位" :show-overflow-tooltip="true" prop="maintenanceUnit" width="200"/>
      <el-table-column label="是否锁定" align="center" width="130">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.locked"
            :active-value=1 :inactive-value=0
            @change="handleLockedStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否有效" align="center" width="130">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.valid"
            :active-value=0 :inactive-value=1
            @change="handleValidStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getPage"
    />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :visible.sync="open" :title="title" width="1000px" append-to-body>
      <el-tabs type="border-card" :before-leave="beforeTagsLeave" v-model="tabs">
        <el-tab-pane label="设备基本信息" name="jbxx">
          <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px">
            <el-col :span="24">
              <el-form-item label="测站编码" prop="stCd">
                <el-input v-model="form.stCd" placeholder="请输入测站编码" show-word-limit clearable
                          :style="{width: '100%'}" maxlength="10" :disabled="dialogType === 'update'"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="测站名称" prop="stName">
                <el-input v-model="form.stName" placeholder="请输入测站名称" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="测站分类" prop="stClassification">
                <el-select v-model="form.stClassification" placeholder="测站分类" clearable size="small"
                           :style="{width: '100%'}">
                  <el-option v-for="dict in dict.type.st_classification"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="测站类型" prop="stType">
                <el-select v-model="form.stType" placeholder="测站类型" clearable size="small" :style="{width: '100%'}">
                  <el-option v-for="dict in dict.type.st_type"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="上报频率" prop="submitFrequency">
                <el-input v-model="form.submitFrequency" placeholder="请输入上报频率（分钟/条）" clearable
                          :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="所属行业类别" prop="industryType">
                <el-select v-model="form.industryType" placeholder="行业类别" clearable size="small"
                           :style="{width: '100%'}">
                  <el-option v-for="dict in dict.type.industry_type"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="所属行政区" prop="adCodeList">
                <el-cascader class="selectArea" :style="{width: '100%'}" :props="defaultParams"
                             :options="options" v-model="form.adCodeList" :clearable="true"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="建设单位" prop="constructionUnit">
                <el-input v-model="form.constructionUnit" placeholder="请输入建设单位" clearable
                          :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="管理单位" prop="managementUnit">
                <el-input v-model="form.managementUnit" placeholder="请输入管理单位" clearable
                          :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="运维单位" prop="maintenanceUnit">
                <el-input v-model="form.maintenanceUnit" placeholder="请输入运维单位" clearable
                          :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否有效" prop="valid" required>
                <el-switch v-model="form.valid" :active-value=0 :inactive-value=1></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否锁定" prop="locked" required>
                <el-switch v-model="form.locked" :active-value=1 :inactive-value=0></el-switch>
              </el-form-item>
            </el-col>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="站点解析规则" name="zjpz">
          <el-transfer v-model="checkGroupList" :titles="['解析组件列表', '选中组件列表']"
                       :props="subGroupListProps" :data="subGroupList"/>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  import {getAdList} from '@/api/common/ad'
  import {
    page,
    getStation,
    insertStation,
    updateStation,
    delStation,
    initCache
  } from "@/api/equipmentmanagement/equipment";
  import {
    getAllElementGroup,
  } from "@/api/analysisconfigure/elementgroup";
  import {
    getAnalysisGroupListByStCd,
    insertStGroup,
  } from "@/api/analysisconfigure/stanalysisgroup";
  import {isEmptyString} from '@/utils/emptyCheck';

  export default {
    dicts: ['st_type', 'industry_type', 'st_classification'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        stCds: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        page: null,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {},
        dialogType: '',
        // 行政区级联选择器
        options: [],
        defaultParams: {
          checkStrictly: true,
          label: 'adName',
          value: 'adCode',
          children: 'children'
        },

        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          stCd: undefined,
          stName: undefined,
          stType: undefined,
          submitFrequency: undefined,
          valid: undefined,
          locked: undefined,
        },
        // 表单校验
        rules: {
          stCd: [{
            required: true,
            message: '请输入测站编码',
            trigger: 'blur'
          }],
          stName: [{
            required: true,
            message: '请输入测站名称',
            trigger: 'blur'
          }],
        },
        tabs: "jbxx",
        subGroupList: [],
        checkGroupList: [],
        subGroupListProps: {
          key: 'id',
          label: 'analysisGroupName'
        },

      };

    },

    created() {
      this.getPage();
      this.adList();
      this.allElementGroup();
    },
    methods: {

      /** 查询分页列表 */
      getPage() {
        this.loading = true;
        page(this.queryParams).then(response => {
            this.page = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.stCds = selection.map(item => item.stCd);
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      // 测站锁定状态修改
      handleLockedStatusChange(row) {
        let text = row.locked === 1 ? "锁定" : "解除锁定";
        this.$modal.confirm('确认要"' + text + '""' + row.stName + '"吗？')
          .then(function () {
            return updateStation(row);
          }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.locked = row.locked === 0 ? 1 : 0;
        });
      },
      // 测站有效状态修改
      handleValidStatusChange(row) {
        let text = row.valid === 0 ? "有效" : "无效";
        this.$modal.confirm('确认要"' + text + '""' + row.stName + '"吗？')
          .then(function () {
            return updateStation(row);
          }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.valid = row.valid === 1 ? 0 : 1;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          stCd: undefined,
          stName: undefined,
          stType: undefined,
          submitFrequency: undefined,
          valid: undefined,
          locked: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getPage();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.title = "新增测站";
        this.open = true;
        this.dialogType = "add";
        this.tabs = "jbxx";
        this.form.valid = 0;
        this.form.locked = 0;

      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.tabs = "jbxx";
        const stCds = row.stCd || this.stCds;
        this.checkElementGroup(stCds);
        getStation(stCds).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改接入测站信息";
          this.dialogType = "update";
          this.adCodeCallBack(response.data.adCode);
        });
      },
      /** 从省市县行政区编码数组中提取最详细的一个行政区编码 */
      adCodesToString(adCodeList) {
        if (adCodeList !== null && adCodeList !== '' && typeof (adCodeList) !== 'undefined') {
          return adCodeList[adCodeList.length - 1];
        }
      },
      async save() {
        let that = this;
        that.form.adCode = that.adCodesToString(that.form.adCodeList);
        // that.form.adCode = that.form.adCodeList[that.form.adCodeList.length - 1];
        let stCd = "";
        let success = false;
        stCd = that.form.stCd;
        if ('update' === that.dialogType) {
          await updateStation(that.form).then(response => {
            success = true;
          });
        } else {
          await insertStation(that.form).then(response => {
            success = true;
          });
        }
        if (success) {
          let checkGroupList = that.checkGroupList;
          insertStGroup(stCd, checkGroupList).then(response => {
            that.$modal.msgSuccess("保存成功");
            that.open = false;
            that.getPage();
          });
        }
      },
      /** 提交按钮 */
      submitForm() {
        let that = this;
        that.$refs["form"].validate(valid => {
          if (valid) {
            that.save();
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const stCds = row.stCd || this.stCds;
        this.$modal.confirm('是否确认删除？').then(function () {
          return delStation(stCds);
        }).then(() => {
          this.getPage();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      // 获取行政区数据
      adList() {
        getAdList().then(response => {
          this.options = response.data
        });
      },
      adCodeCallBack(adCode) {
        if (adCode !== "" && adCode !== null) {
          let adCodeList = [];
          if (adCode.endsWith("0000")) {
            adCodeList.push(adCode.substring(0, 6));
          } else if (adCode.endsWith("00")) {
            adCodeList.push(adCode.substring(0, 2) + "0000");
            adCodeList.push(adCode.substring(0, 6));
          } else {
            adCodeList.push(adCode.substring(0, 2) + "0000");
            adCodeList.push(adCode.substring(0, 4) + "00");
            adCodeList.push(adCode.substring(0, 6));
          }
          this.form.adCodeList = adCodeList;
        }
      },
      allElementGroup() {
        getAllElementGroup("").then(response => {
          const subGroupList = response.data;
          if (subGroupList == null || subGroupList === "") {
            this.subGroupList = [];
          } else {
            this.subGroupList = subGroupList;
          }
        });
      },
      checkElementGroup(stCd) {
        getAnalysisGroupListByStCd(stCd).then(response => {
          const checkGroupList = response.data;
          this.checkGroupList = [];
          if (checkGroupList !== null && checkGroupList !== "") {
            for (const key of checkGroupList) {
              this.checkGroupList.push(key.id);
            }
          }
        });
      },
      // 控制标签页的切换，未完成指定内容填写不允许切换
      beforeTagsLeave(activeName, oldActiveName) {
        let that = this;
        let nextAble = false;
        if (oldActiveName === 'jbxx') {
          that.$refs["form"].validate(valid => {
            if (valid) {
              nextAble = true;
            }
          });
          if (!nextAble) {
            // 不满足条件则发起错误提醒
            this.$message.error('请先完成设备基本信息');
            return false
          }
        } else if (oldActiveName === '1') {

        }
      },
      handleInitCache() {
        this.$confirm('此操作将删除缓存中原有配置，并从数据库中加载最新配置信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          initCache().then(response => {
            this.$message({
              type: 'success',
              message: '初始化成功!'
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/user/export', {
          ...this.queryParams
        }, `user_${new Date().getTime()}.xlsx`)
      },
    }
  }
  ;
</script>

<style scoped="scoped">
  /deep/ .el-tabs {
    width: 100%;
  }

  /deep/ .el-transfer {
    width: 100%;
    height: 500px;
  }

  /deep/ .el-transfer .el-transfer-panel {
    width: 40%;
    height: 100%;
  }

  /deep/ .el-transfer-panel__body {
    height: 100%;
  }

  /deep/ .el-transfer-panel__body div {
    height: 100%;
  }


</style>
